import { View, Text, ScrollView, Image } from '@tarojs/components'
import Taro, { useRouter } from '@tarojs/taro'
import { FC, useState } from 'react'
import { firstValueFrom } from 'rxjs'
import { softWarePrice, subsOrderParam } from '@/models/request/userReq'
import { useAuthFacade } from '@/hooks/useAuthFacade'
import CONFIG from "@/config";
import './index.scss'

export const Pay: FC = () => {

  const [authFacade, loginStatus, userId, , , userInfo] = useAuthFacade();

  const router = useRouter();
  const [price, setPrice] = useState(Number(router.params.priceMonth))
  const [yearPrice, setyearPrice] = useState(Number(router.params.priceYear))
  const [planName, setPlanName] = useState(router.params.planName || '')
  const [current, SetCurrent] = useState(Number(router.params.current))
  const [currentPlanId, setCurrentPlanId] = useState(router.params.planId)
  const [roundsVal, setRoundsVal] = useState(Number(router.params.roundsVal))

  const [payIndex, setPayIndex] = useState(0) 
  //  旗舰版单场套餐
  const roundsList = [
    {
      rounds: 10,
      priceRound: 500,
      total: 500 * 10,
    },
    {
      rounds: 1,
      priceRound: 500,
      total: 500 * 1,
    },
    {
      rounds: roundsVal === 0 ? '自定义' : roundsVal,
      priceRound: 500,
      total: 500 * roundsVal,
    },
  ]

  // 套餐类型与价格
  const priceList: softWarePrice[] = [
    {
      priceTime: '一年',
      total: yearPrice,
      discount: yearPrice - (price * 12),
      oldTotal: price * 12
    },
    {
      priceTime: '三个月',
      total: price * 3,
    },
    {
      priceTime: '一个月',
      total: price,
    },
  ]

 
  // 支付方式
  const payList = [
    {
      logo: 'https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/service_WX.png',
      name: '微信支付',
      circle: "https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/pay_circle.png",
      checked: "https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/pay_checked.png"
    }, 
  ]

  // 点击套餐价格
  const handleCheckPrice = (e) => {
    console.log('点击触发', e, e.currentTarget.dataset);
    const index = e.currentTarget.dataset.index;
    SetCurrent(index)
  }

  // 点击支付方式
  const handleSelectPay = (e) => {
    const index = e.currentTarget.dataset.select;
    console.log('点击触发', e, e.currentTarget.dataset, index);
    setPayIndex(index)
  }

  // 跳转支付页
  const goToPay = async () => {
    console.log('待支付金额', priceList[current].total);
    let counts=0
    //购买数量
    if (priceList[current].total===yearPrice){
        counts=12
    }else{
       counts = priceList[current].total / price
    } 
    const rounds = roundsList[current].rounds as number
    const params = {} as subsOrderParam
    params.planId = currentPlanId as string
    params.appId = CONFIG.APPID
    params.amount = counts || rounds
    const res = await firstValueFrom(authFacade.createSubsOrders(params)) 
    console.log('下单的参数：', res)
    Taro.requestPayment({
      timeStamp: res.timeStamp,
      nonceStr: res.nonceStr,
      package: res.package,
      signType: res.signType,
      paySign: res.paySign,
      fail: (err)=> {
        console.log('取消支付：', err) 
        //取消支付更新支付码
        authFacade.cancelOrder(res.mchOrderId)
      }
    })
  }  

  return (
    <View className='main'>
      {/* 套餐时限 */}
      <View className='select'>
        <View>
          <Text className='select-title'>开通服务</Text>
          <Text className='select-name'>{planName}</Text> 
          {
            planName !== '旗舰版单场' && (
          <ScrollView className='scroll-view' scrollX>
            {priceList.map((item, index) => (
              <View className={index === current ? "scroll-item current-item" : "scroll-item"} onClick={handleCheckPrice} data-index={index} key={index}>
                <View className='item-style'>
                  <View className='item-time'>{item.priceTime}</View>
                  <View className='item-price'>￥<Text style='font-size:24px; font-weight: 500'>{item.total}</Text></View>
                  {
                    item.priceTime === '一年' && (
                      <View>
                        <View className='item-del'>￥{item.oldTotal}</View>
                        <View className='item-discount'>立减{item.discount}元</View>
                      </View>
                    )
                  }
                </View>
              </View>
            ))}
          </ScrollView> 
            )
          } 

          {
            planName==='旗舰版单场' &&(
              <ScrollView className='scroll-view' scrollX>
                {
                  roundsList.map((item, index1) => (
                    <View className={index1 === current ? "scroll-item1 current-item" : "scroll-item1"} onClick={handleCheckPrice} data-index={index1} key={index1}>
                      <View className='itemStyle'>
                        <View className='item-num'>{item.rounds}
                          {
                            item.rounds !== '自定义' && (
                              <Text className='site'>场</Text>
                            )
                          }
                        </View>
                        <View className='item-price'>￥{item.priceRound}/场</View>
                      </View>
                    </View>
                  ))
                }
              </ScrollView>
            )
          } 
        </View> 
      </View>
      {/* 支付方式 */}
      <View className='pay-style'>
        <View className='pay-title'>支付方式</View>
        {payList.map((item, index) => (
          <View className='pay-select' onClick={handleSelectPay} data-select={index} key={index}>
            <View className='pay-select-view'>
              <Image src={item.logo}></Image>
              <Text className='pay-name'>{item.name}</Text>
            </View>
            <View className='pay-select-view'>
              <Image src={payIndex === index ? item.checked : item.circle} style='width: 18px; height: 18px;'></Image>
            </View>
          </View>
        ))}
      </View>

      {/* 立即支付 */}
      <View className='activation-code' onClick={goToPay}>
        <Text>立刻支付</Text>
      </View>
    </View>
  )
}

export default Pay

